package app

import (
	"context"
	"fmt"
	"log"

	"github.com/containerd/containerd"
	"github.com/containerd/containerd/cio"
	"github.com/urfave/cli/v2"
)

var RmCommand = &cli.Command{
	Name:      "rm",
	Usage:     "remove one or more container",
	ArgsUsage: "[flags] CONTAINER [CONTAINER, ...]",
	Flags: []cli.Flag{
		&cli.BoolFlag{
			Name:    "force",
			Aliases: []string{"f"},
			Value:   false,
			Usage:   "Force delete container",
		},
	},
	Action: func(context *cli.Context) error {
		var (
			force = context.Bool("force")
		)

		client, ctx, cancel, err := NewClient(context)
		if err != nil {
			return err
		}
		defer cancel()

		deleteOpts := []containerd.DeleteOpts{}
		if context.NArg() == 0 {
			return fmt.Errorf("must specify at least one container to delete")
		}

		for _, id := range context.Args().Slice() {
			if err := deleteContainer(ctx, client, id, force, deleteOpts...); err != nil {
				log.Fatal(err)
			} else {
				log.Println(id)
			}
		}

		return nil
	},
}

func deleteContainer(ctx context.Context, client *containerd.Client, id string, force bool, opts ...containerd.DeleteOpts) error {
	container, err := client.LoadContainer(ctx, id)
	if err != nil {
		return err
	}
	task, err := container.Task(ctx, cio.Load)
	if err != nil {
		err = container.Delete(ctx, opts...)
		if err != nil {
			return err
		}
		return nil
	}
	status, err := task.Status(ctx)
	if err != nil {
		return err
	}
	if !force && status.Status != containerd.Stopped && status.Status != containerd.Created {
		return fmt.Errorf("cannot delete a non stopped container: %v %v", id, status.Status)
	} else {
		var dOpts []containerd.ProcessDeleteOpts
		dOpts = append(dOpts, containerd.WithProcessKill)
		_, err := task.Delete(ctx, dOpts...)
		if err != nil {
			return err
		}
		err = container.Delete(ctx, opts...)
		if err != nil {
			return err
		}
	}
	return nil
}
